#include <drogon/drogon.h>
#include <iostream>
#include <string.h>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <thread>
#include <chrono>
using namespace std;
/*ping通返回0，ping不通一直等待*/

int go_ping(const char *svrip)
{
        string hear = "insert into ipaddr values(\"";
        string tail = "\")";
        string strquerysentence = "";

        char command[100];
        int status;
        sprintf(command,"ping -c 1 -q %s > /dev/null 2>&1",svrip);
        status=system(command);
        if(status==0)
        {
                 auto clientPtr = drogon::app().getDbClient();
                strquerysentence = hear + svrip + tail;
                clientPtr->execSqlAsyncFuture(strquerysentence);
                return 0;
        }
        else
        {
                return 1;
        }
        return 0;
}

int pingid(int n)
{
        string strIP = "192.168.103.";
        string strj = "";
        string strz = "";
        for (int i = n * 32; i < ((n + 1) * 32); i++)
        {
                strj = to_string(i);
                strz = strIP + strj;
                // cout<<strz<<endl;
                go_ping(strz.c_str());
        }
        return 0;
}

int createping()
{
        std::this_thread::sleep_for(std::chrono::seconds(5));
        auto clientPtr = drogon::app().getDbClient();
        while (1)
        {
                clientPtr->execSqlAsyncFuture("delete from ipaddr");
                thread t1(pingid, 0);
                thread t2(pingid, 1);
                thread t3(pingid, 2);
                thread t4(pingid, 3);
                thread t5(pingid, 4);
                thread t6(pingid, 5);
                thread t7(pingid, 6);
                thread t8(pingid, 7);
                t1.detach();
                t2.detach();
                t3.detach();
                t4.detach();
                t5.detach();
                t6.detach();
                t7.detach();
                t8.join();
                std::this_thread::sleep_for(std::chrono::seconds(10));
        }
}

int main()
{

        thread tt(createping);
        tt.detach();
        // Set HTTP listener address and port
        drogon::app().addListener("0.0.0.0", 8888);
        // Load config file
        drogon::app().loadConfigFile("../config.json");
        // Run HTTP framework,the method will block in the internal event loop
        drogon::app().run();

        return 0;
}
